package com.paiai.lslease.service.apphouse;

import com.dsmzg.base.dto.ssh.ConnectInfo;
import com.dsmzg.base.util.ioutil.SSHFileUtil;
import com.paiai.lslease.auto.dao.*;
import com.paiai.lslease.auto.model.*;
import com.paiai.lslease.base.FTPConstants;
import com.paiai.lslease.dao.apphouse.AppHouseDiyDAO;
import com.paiai.lslease.dao.apphouse.AppLockTenantInfoDAO;
import com.paiai.lslease.dao.apphouse.AppTenantInfoDAO;
import com.paiai.lslease.model.*;
import com.paiai.lslease.service.appuser.AppSysUserService;
import com.paiai.lslease.service.landlordauth.AppLandlordAuthService;
import com.paiai.lslease.util.FatherToChildUtils;
import com.paiai.lslease.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.lang.reflect.Method;
import java.util.*;

@Service("appHouseService")
public class AppHouseServiceImpl implements AppHouseService {

    private static final Logger loggger = LoggerFactory.getLogger(AppHouseServiceImpl.class);

    private AppHouseDAO appHouseDAO;
    private AppFurnitureDAO appFurnitureDAO;
    private AppPicDAO appPicDAO;
    private AppHouseDiyDAO appHouseDiyDAO;
    private AppSocketDAO appSocketDAO;
    private AppLockDAO appLockDAO;
    private AppLockTenantDAO appLockTenantDAO;
    private AppSysUserService appSysUserService;
    private AppTenantInfoDAO appTenantInfoDAO;
    @Autowired
    private AppLandlordAuthService appLandlordAuthService;

    public void setAppHouseDAO(AppHouseDAO appHouseDAO) {
        this.appHouseDAO = appHouseDAO;
    }

    public void setAppFurnitureDAO(AppFurnitureDAO appFurnitureDAO) {
        this.appFurnitureDAO = appFurnitureDAO;
    }

    public void setAppPicDAO(AppPicDAO appPicDAO) {
        this.appPicDAO = appPicDAO;
    }

    public void setAppHouseDiyDAO(AppHouseDiyDAO appHouseDiyDAO) {
        this.appHouseDiyDAO = appHouseDiyDAO;
    }

    public void setAppSocketDAO(AppSocketDAO appSocketDAO) {
        this.appSocketDAO = appSocketDAO;
    }

    public void setAppLockDAO(AppLockDAO appLockDAO) {
        this.appLockDAO = appLockDAO;
    }

    public void setAppLockTenantDAO(AppLockTenantDAO appLockTenantDAO) {
        this.appLockTenantDAO = appLockTenantDAO;
    }

    public void setAppSysUserService(AppSysUserService appSysUserService) {
        this.appSysUserService = appSysUserService;
    }

    public void setAppTenantInfoDAO(AppTenantInfoDAO appTenantInfoDAO) {
        this.appTenantInfoDAO = appTenantInfoDAO;
    }

    public AppHouseInfo insertAppHouseInfo(AppHouse appHouse) throws Exception {
        //保存房源基本信息
        appHouse.setCompanyId(1);//通过app添加的房源，公司属性默认为运营平台-总公司
        appHouse.setInsertTime(new Date());
        appHouse.setUpdateTime(new Date());
        appHouse.setItem1("1");
        appHouseDAO.insert(appHouse);
        //添加房源的用户增加房东属性
//            AppSysUserRoleExample appSysUserRoleExample = new AppSysUserRoleExample();
//            appSysUserRoleExample.createCriteria().andUserIdEqualTo(appHouse.getLandlordId());
//            List<AppSysUserRole> appSysUserRoleList;
//            appSysUserRoleList = appSysUserRoleDAO.selectByExample(appSysUserRoleExample);
//            if (appSysUserRoleList == null || appSysUserRoleList.size() == 0) {
//                return null;
//            }
//            AppSysUserRole appSysUserRole = appSysUserRoleList.get(0);
//            appSysUserRole.setRoleId(appSysUserService.getLandlordRoleId());
//            appSysUserRole.setUpdateTime(new Date());
//            appSysUserRoleDAO.updateByPrimaryKey(appSysUserRole);
        if (!appSysUserService.addLandlordRoleToUserById(appHouse.getLandlordId())) {
            loggger.info("添加房源的用户增加房东属性失败");
            throw new Exception();
        }
        return getAppHouseInfo(appHouseDiyDAO.getNeweastAppHouseId());
    }

    public AppHouseInfo modifyAppHouseBaseInfo(int houseId, AppHouse appHouse) throws Exception {
//        AppHouseExample appHouseExample = new AppHouseExample();
//        appHouseExample.createCriteria().andLandlordIdEqualTo(userId).andIdEqualTo(houseId).andItem1EqualTo("1");
//        List<AppHouse> appHouseList = appHouseDAO.selectByExample(appHouseExample);
//        if (appHouseList == null || appHouseList.size() == 0) {
//            loggger.debug("未查询到用户的房源信息，请确认该用户是否是房东");
//            return null;
//        }
        appHouse.setId(houseId);
        appHouse.setUpdateTime(new Date());
        appHouseDAO.updateByPrimaryKeySelective(appHouse);
        return getAppHouseInfo(houseId);
    }

    public AppHouseInfo modifyAppHouseFurnitureInfo(int houseId, AppFurniture appFurniture) throws Exception {
        AppHouseInfo appHouseInfo = getAppHouseInfo(houseId);
//        if (appHouseInfo == null || appHouseInfo.getLandlordId() != userId) {
//            loggger.debug("未查询到用户的房源信息，请确认该用户是否是房东");
//            return null;
//        }
        //新增新的家具
        appFurniture.setItem1("1");
        appFurniture.setInsertTime(new Date());
        appFurniture.setUpdateTime(new Date());
        appFurnitureDAO.insert(appFurniture);
        if (appHouseInfo.getHouseFurnitureId() != null && appHouseInfo.getHouseFurnitureId() > 0) {//之前存储过家具
            //把之前的家具标记为删除
            AppFurniture appFurniture1 = appFurnitureDAO.selectByPrimaryKey(appHouseInfo.getHouseFurnitureId());
            appFurniture1.setItem1("-1");
            appFurnitureDAO.updateByPrimaryKey(appFurniture1);
        }
        //更新房源的家具ID
        AppHouse appHouse = appHouseDAO.selectByPrimaryKey(houseId);
        appHouse.setHouseFurnitureId(appHouseDiyDAO.getNeweastAppFurnitureId());
        appHouse.setUpdateTime(new Date());
        appHouseDAO.updateByPrimaryKey(appHouse);
        return getAppHouseInfo(houseId);
    }

    public AppHouseInfo modifyAppHousePicInfo(int houseId, File housePic, String housePicFileName, String housePicContentType, int housePicIndex) throws Exception {
        AppHouseInfo appHouseInfo = getAppHouseInfo(houseId);
        //修改图片
        AppPic appPic = new AppPic();
        byte[] bytes = FileUtil.file2byte(housePic);
        loggger.info("root=" + FTPConstants.photoPath+ "photo size:" + bytes.length);
        if (bytes.length > 530000) {// 用户图像不能超过512k
            loggger.debug("图像超过了512k，已被过滤");
            return null;
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ConnectInfo connectInfo = new ConnectInfo(FTPConstants.host, FTPConstants.username, FTPConstants.password);
        String resultname;
        resultname = SSHFileUtil.transFile(FTPConstants.photoPath,"png",connectInfo,bais);
        String picAddress = FTPConstants.photoServer+ resultname;
        loggger.info("图像上传完成,在服务器的路径为:" + picAddress);
        Method setPicX = AppPic.class.getMethod("setPic"  + (housePicIndex + 1), String.class);
        if (appHouseInfo.getHousePicId() != null && appHouseInfo.getHousePicId() > 0) {//之前存储过图片
            //更新图片信息
            AppPic appPic1 = appPicDAO.selectByPrimaryKey(appHouseInfo.getHousePicId());
            setPicX.invoke(appPic1, picAddress);
            appPic1.setUpdateTime(new Date());
            appPicDAO.updateByPrimaryKey(appPic1);
        } else {//之前没有保存过图片，保存
            setPicX.invoke(appPic, picAddress);
            appPic.setItem1("1");
            appPic.setUpdateTime(new Date());
            appPic.setInsertTime(new Date());
            appPicDAO.insert(appPic);
            //更新房源的图片ID
            AppHouse appHouse = appHouseDAO.selectByPrimaryKey(houseId);
            appHouse.setHousePicId(appHouseDiyDAO.getNeweastAppPicId());
            appHouse.setUpdateTime(new Date());
            appHouseDAO.updateByPrimaryKey(appHouse);
        }
        return getAppHouseInfo(houseId);
    }

    public AppHouseInfo getAppHouseInfo(int houseId) throws Exception {
        //根据房源ID获取房源基本信息
        AppHouseInfo appHouseInfo = new AppHouseInfo();
        AppHouse appHouse = getAppHouseById(houseId);
        FatherToChildUtils.fatherToChild(appHouse, appHouseInfo);
        AppFurniture appFurniture = getAppFurniture(houseId);
        AppPic appPic = getAppPic(houseId);
        appHouseInfo.setAppFurniture(appFurniture);
        appHouseInfo.setAppPic(appPic);
        return appHouseInfo;
    }

    public List getApphouseInfoList(int userId) throws Exception {
        List appHouseInfoList = new ArrayList();
        //查询该用户是房东还是租客
        boolean belongLandlord = appSysUserService.userBelongLandlord(userId);
        boolean belongTenant = appSysUserService.userBelongTenant(userId);
        boolean belongLandlordAuthManager = appSysUserService.userBelongLandlordAuthManagerById(userId);
        if (belongLandlord) {
            appHouseInfoList.addAll(selectHouseLockListByLandlordId(userId));
        }
        if (belongTenant) {
            appHouseInfoList.addAll(selectLockTenantListByTenantId(userId));
        }
        if (belongLandlordAuthManager) {
            List<AppHouseInfoLandlordQuery> appHouseInfoLandlordQueryList = selectHouseLockListByLandlordAuthManagerId(userId);
            if (appHouseInfoLandlordQueryList != null) {
                appHouseInfoList.addAll(appHouseInfoLandlordQueryList);
            }
        }
        return appHouseInfoList;
    }

    public AppFurniture getAppFurniture(int houseId) throws Exception {
        AppHouse appHouse;
        appHouse = getAppHouseById(houseId);
        if (appHouse == null || appHouse.getHouseFurnitureId() == null) {
            return null;
        }
        AppFurnitureExample appFurnitureExample = new AppFurnitureExample();
        appFurnitureExample.createCriteria().andIdEqualTo(appHouse.getHouseFurnitureId());
        List<AppFurniture> appFurnitureList;
        appFurnitureList = appFurnitureDAO.selectByExample(appFurnitureExample);
        return appFurnitureList == null || appFurnitureList.size() == 0 ? null : appFurnitureList.get(0);
    }

    public AppPic getAppPic(int houseId) throws Exception {
        AppHouse appHouse;
        appHouse = getAppHouseById(houseId);
        if (appHouse == null || appHouse.getHousePicId() == null) {
            return null;
        }
        AppPicExample appPicExample = new AppPicExample();
        appPicExample.createCriteria().andIdEqualTo(appHouse.getHousePicId());
        List<AppPic> appPicList = appPicDAO.selectByExample(appPicExample);
        return appPicList == null || appPicList.size() == 0 ? null : appPicList.get(0);
    }

    public AppHouse getAppHouseById(int houseId) throws Exception {
        AppHouseExample appHouseExample = new AppHouseExample();
        appHouseExample.createCriteria().andIdEqualTo(houseId).andItem1EqualTo("1");
        List<AppHouse> appHouseList = appHouseDAO.selectByExample(appHouseExample);
        return appHouseList == null || appHouseList.size() == 0 ? null : appHouseList.get(0);
    }

    public boolean deleteAppHouseById(int houseId) throws Exception {
//        AppHouseExample appHouseExample = new AppHouseExample();
//        appHouseExample.createCriteria().andLandlordIdEqualTo(userId).andIdEqualTo(houseId).andItem1EqualTo("1");
//        List<AppHouse> appHouseList = appHouseDAO.selectByExample(appHouseExample);
//        if (appHouseList == null || appHouseList.size() == 0) {
//            return "未查询到用户的房源信息，请确认该用户是否是房东";
//        }
//        AppHouse appHouse = appHouseList.get(0);
        //删除房源的所有网关信息
        AppSocketExample appSocketExample = new AppSocketExample();
        appSocketExample.createCriteria().andHouseIdEqualTo(houseId);
        List<AppSocket> appSocketList;
        appSocketList = appSocketDAO.selectByExample(appSocketExample);
        for (AppSocket appSocket : appSocketList) {
            appSocket.setItem1("-1");
            appSocket.setUpdateTime(new Date());
            appSocketDAO.updateByPrimaryKey(appSocket);
        }
        //删除房源下所有设备下的所有住户
        AppLockExample appLockExample = new AppLockExample();
        appLockExample.createCriteria().andHouseIdEqualTo(houseId);
        List<AppLock> appLockList = appLockDAO.selectByExample(appLockExample);
        for (AppLock appLock : appLockList) {
            AppLockTenantExample appLockTenantExample = new AppLockTenantExample();
            appLockTenantExample.createCriteria().andLockIdEqualTo(appLock.getId());
            List<AppLockTenant> appLockTenantList = appLockTenantDAO.selectByExample(appLockTenantExample);
            for (AppLockTenant appLockTenant : appLockTenantList) {
                appLockTenant.setItem1("-1");
                appLockTenant.setUpdateTime(new Date());
                appLockTenantDAO.updateByPrimaryKey(appLockTenant);
            }
        }
        //删除房源所有的设备信息
        for (AppLock appLock : appLockList) {
            appLock.setItem1("-1");
            appLock.setUpdateTime(new Date());
            appLockDAO.updateByPrimaryKey(appLock);
        }
        //删除房源信息
        AppHouse appHouse = getAppHouseById(houseId);
        appHouse.setItem1("-1");
        appHouse.setUpdateTime(new Date());
        appHouseDAO.updateByPrimaryKey(appHouse);
        //如果删除的是房东的最后一个房源，删除房源后去掉用户的房东角色
        List<AppHouse> appHouseList = selectSimpleHouseList(appHouse.getLandlordId());
        if (appHouseList != null && appHouseList.size() == 0 && !appSysUserService.deleteLandlordRoleToUserById(appHouse.getLandlordId())) {
            loggger.info("删除的是房东的最后一个房源，删除房源后去掉用户的房东角色失败");
            return false;
        }
        return true;
    }

    @Override
    public boolean checkHouseExist(int houseId) throws Exception {
        return getAppHouseById(houseId) != null;
    }

    @Override
    public boolean houseBelongUser(int houseId, int userId) throws Exception {
        AppHouseExample appHouseExample = new AppHouseExample();
        appHouseExample.createCriteria().andLandlordIdEqualTo(userId).andItem1EqualTo("1");
        List<AppHouse> appHouseList = appHouseDAO.selectByExample(appHouseExample);
        if (appHouseList != null) {
            for (AppHouse appHouse : appHouseList) {
                if (appHouse.getId() == houseId) {
                    return true;
                }
            }
        }
        AppSysUser appSysUser = appSysUserService.getAppSysUserInfoById(userId);
        if (appSysUser != null) {
            List<AppLandlordAuthHouseInfo> appLandlordAuthList = appLandlordAuthService.selectAppLandlordAuthListByUserMobile(appSysUser.getMobile());
            if (appLandlordAuthList != null) {
                for (AppLandlordAuthHouseInfo appLandlordAuth : appLandlordAuthList) {
                    if (houseId == appLandlordAuth.getId()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public List<AppHouse> selectSimpleHouseList(int userId) throws Exception {
        List<AppHouse> appHouseInfoList = new ArrayList<AppHouse>();
        boolean belongLandlord = appSysUserService.userBelongLandlord(userId);
        boolean belongTenant = appSysUserService.userBelongTenant(userId);
        boolean belongLandlordAuthManager = appSysUserService.userBelongLandlordAuthManagerById(userId);
        if (belongLandlord) {
            //查询房东所有的房源列表
            AppHouseExample appHouseExample = new AppHouseExample();
            appHouseExample.createCriteria().andLandlordIdEqualTo(userId).andItem1EqualTo("1");
            List<AppHouse> appHouseList = appHouseDAO.selectByExample(appHouseExample);
            if (appHouseList != null) {
                appHouseInfoList.addAll(appHouseList);
            }
        }
        if (belongTenant) {
            //查询租客租住了的房源列表
            List<Integer> tenantAllHouseId = appTenantInfoDAO.getTenantAllHouseId(userId);
            if (tenantAllHouseId != null) {
                for (Integer houseId : tenantAllHouseId) {
                    appHouseInfoList.add(appHouseDAO.selectByPrimaryKey(houseId));
                }
            }
        }
        if (belongLandlordAuthManager) {
            //查询用户信息
            AppSysUser appSysUser = appSysUserService.getAppSysUserInfoById(userId);
            if (appSysUser != null) {
                //查询房东授权管理员的房源列表
                List<AppLandlordAuth> appLandlordAuthList = appLandlordAuthService.queryAppLandlordAuthListByUserMobile(appSysUser.getMobile());
                if (appLandlordAuthList != null) {
                    for (AppLandlordAuth appLandlordAuth : appLandlordAuthList) {
                        appHouseInfoList.add(appHouseDAO.selectByPrimaryKey(appLandlordAuth.getHuoseId()));
                    }
                }
            }
        }
        return appHouseInfoList;
    }

    @Override
    public List<AppLock> selectAppLockListByHouseId(int houseId) throws Exception {
        AppLockExample appLockExample = new AppLockExample();
        appLockExample.createCriteria().andHouseIdEqualTo(houseId).andItem1EqualTo("1");
        return appLockDAO.selectByExample(appLockExample);
    }

    /**
     * 查询房东的房源与设备列表
     */
    private List<AppHouseInfoLandlordQuery> selectHouseLockListByLandlordId(int userId) throws Exception {
        List<AppHouseInfoLandlordQuery> appHouseInfoLandlordQueryList = new ArrayList<AppHouseInfoLandlordQuery>();
        //查询房东所有的房源列表
        AppHouseExample appHouseExample = new AppHouseExample();
        appHouseExample.createCriteria().andLandlordIdEqualTo(userId).andItem1EqualTo("1");
        List<AppHouse> appHouseList = appHouseDAO.selectByExample(appHouseExample);
        if (appHouseList != null) {
            for (AppHouse appHouse : appHouseList) {
                AppHouseInfoLandlordQuery appHouseInfoLandlordQuery = new AppHouseInfoLandlordQuery();
                FatherToChildUtils.fatherToChild(appHouse, appHouseInfoLandlordQuery);
                AppLockExample appLockExample = new AppLockExample();
                appLockExample.createCriteria().andHouseIdEqualTo(appHouse.getId()).andItem1EqualTo("1");
                List<AppLock> appLockList = appLockDAO.selectByExample(appLockExample);
                appHouseInfoLandlordQuery.setAppLockList(appLockList);
                appHouseInfoLandlordQuery.setQueryUserId(userId);
                appHouseInfoLandlordQuery.setQueryUserHasManagePermisstion(1);
                appHouseInfoLandlordQueryList.add(appHouseInfoLandlordQuery);
            }
        }
        return appHouseInfoLandlordQueryList;
    }

    /**
     * 显示租客的房源与设备列表
     */
    private List<AppHouseInfoTenantQuery> selectLockTenantListByTenantId(int userId) throws Exception {
        List<AppHouseInfoTenantQuery> appHouseInfoTenantQueryList = new ArrayList<AppHouseInfoTenantQuery>();
        //查询租客租住了的房源ID列表
        List<Integer> tenantAllHouseId = appTenantInfoDAO.getTenantAllHouseId(userId);
        loggger.info("租客ID=" + userId + ",客租住了的房源ID列表=" + tenantAllHouseId);
        for (Integer houseId : tenantAllHouseId) {
            AppHouseInfoTenantQuery appHouseInfoTenantQuery = new AppHouseInfoTenantQuery();
            AppHouse appHouse = appHouseDAO.selectByPrimaryKey(houseId);
            if ("1".equalsIgnoreCase(appHouse.getItem1())) {
                FatherToChildUtils.fatherToChild(appHouse, appHouseInfoTenantQuery);
                appHouseInfoTenantQuery.setQueryUserId(userId);
                appHouseInfoTenantQuery.setQueryUserHasManagePermisstion(0);
                HouseLockQuery houseLockQuery = new HouseLockQuery();
                houseLockQuery.setHouseId(houseId);
                houseLockQuery.setTenantId(userId);
                List<LockExternal> lockExternalList = appHouseDiyDAO.selectLockTenantList(houseLockQuery);
                appHouseInfoTenantQuery.setLockExternalList(lockExternalList);
                appHouseInfoTenantQueryList.add(appHouseInfoTenantQuery);
            }
        }
        return appHouseInfoTenantQueryList;
    }

    /**
     * 显示房东授权管理员的所有房源列表
     */
    private List<AppHouseInfoLandlordQuery> selectHouseLockListByLandlordAuthManagerId(int userId) throws Exception {
        List<AppHouseInfoLandlordQuery> appHouseInfoLandlordQueryList = new ArrayList<AppHouseInfoLandlordQuery>();
        //查询用户信息
        AppSysUser appSysUser = appSysUserService.getAppSysUserInfoById(userId);
        if (appSysUser == null) {
            return null;
        }
        //查询房东授权管理员的房源列表
        List<AppLandlordAuthHouseInfo> appLandlordAuthList = appLandlordAuthService.selectAppLandlordAuthListByUserMobile(appSysUser.getMobile());
        if (appLandlordAuthList == null || appLandlordAuthList.size() == 0) {
            return null;
        }
        for (AppLandlordAuthHouseInfo appLandlordAuth : appLandlordAuthList) {
            AppHouseInfoLandlordQuery appHouseInfoLandlordQuery = new AppHouseInfoLandlordQuery();
            AppHouse appHouse = appHouseDAO.selectByPrimaryKey(appLandlordAuth.getId());
            FatherToChildUtils.fatherToChild(appHouse, appHouseInfoLandlordQuery);
            AppLockExample appLockExample = new AppLockExample();
            appLockExample.createCriteria().andHouseIdEqualTo(appLandlordAuth.getId()).andItem1EqualTo("1");
            List<AppLock> appLockList = appLockDAO.selectByExample(appLockExample);
            appHouseInfoLandlordQuery.setAppLockList(appLockList);
            appHouseInfoLandlordQuery.setQueryUserId(userId);
            appHouseInfoLandlordQuery.setQueryUserHasManagePermisstion(1);
            appHouseInfoLandlordQueryList.add(appHouseInfoLandlordQuery);
        }
        return appHouseInfoLandlordQueryList;
    }
}
